import { comonHandlers } from "../handlers";
import "./index.css";

export default function initBusFrame(
  url: string,
  getHandler?: (
    iframe: HTMLIFrameElement
  ) => Record<string, (...args: any[]) => any>,
  useProxy = true
) {
  const iframe = document.createElement("iframe");
  iframe.setAttribute("frameBorder", "0");
  const handlers = getHandler ? getHandler(iframe) : {};
  window.addEventListener("message", async (e: MessageEvent) => {
    if (!e.data || !e.data.type) {
      return;
    }
    const target = iframe.contentWindow!;
    try {
      let data: any;
      if (handlers[e.data.type]) {
        data = await handlers[e.data.type](...e.data.args);
      } else {
        if (useProxy) {
          data = await chrome.extension
            .getBackgroundPage()!
            // @ts-ignore
            .evaluate(e.data);
        } else {
          data = await comonHandlers[e.data.type](...e.data.args);
        }
      }
      target.postMessage(
        {
          code: 200,
          data,
          uid: e.data.uid,
        },
        "*"
      );
    } catch (err) {
      console.error(err);
      target.postMessage(
        {
          code: 501,
          message: err.message,
          uid: e.data.uid,
        },
        "*"
      );
    }
  });
  iframe.onload = () => {
    const ele = document.querySelector<HTMLDivElement>(".page-loading-warp")!;
    ele?.parentElement!.removeChild(ele);
  };
  iframe.src = url
  document.body.appendChild(iframe);
}
